package common

import (
	"encoding/json"
	"gitee.com/game_diamond/model/room"
	"gitee.com/game_diamond/protocols"
	"gitee.com/game_diamond/server"
	"gitee.com/game_diamond/session"
)

func SendMessageToRoomAll(fromId int, body *protocols.WebSocketBody) error {
	ss := session.GetGlobalStudentSession(fromId)
	r, err := room.FindRoom(ss.RoomId)
	if err != nil {
		return err
	}
	msg, _ := json.Marshal(body)
	for _, id := range r.GetAllUserIds() {
		server.WriteSocketMsg(id, msg)
	}
	return nil
}

func SendMessageToRoomStudent(fromId int, body *protocols.WebSocketBody) error {
	ss := session.GetGlobalStudentSession(fromId)
	r, err := room.FindRoom(ss.RoomId)
	if err != nil {
		return err
	}
	msg, _ := json.Marshal(body)
	for _, id := range r.GetAllStudentIds() {
		server.WriteSocketMsg(id, msg)
	}
	return nil
}

func SendMessageToRoomTeacher(fromId int, body *protocols.WebSocketBody) error {
	ss := session.GetGlobalStudentSession(fromId)
	r, err := room.FindRoom(ss.RoomId)
	if err != nil {
		return err
	}
	msg, _ := json.Marshal(body)
	server.WriteSocketMsg(r.GetTeacherId(), msg)
	return nil
}

func SendMessageToUser(fromId int, body *protocols.WebSocketBody, toUserIds ...int) error {
	msg, _ := json.Marshal(body)
	for _, id := range toUserIds {
		server.WriteSocketMsg(id, msg)
	}
	return nil
}
